<?php

namespace we;


use think\facade\Config;
use think\facade\Db;
use think\facade\Request;

// use think\facade\Session;

class AppInit
{
    public function handle($param = [])
    {
        // 事件监听处理
        if (!empty($param['uniacid'])) {
            $uniacid = $param['uniacid'];
        } else if (Request::has('uniacid')) {
            $uniacid = Request::param('uniacid');
        } else if (Request::header('uniacid')) {
            $uniacid = Request::header('uniacid');
        } else if (cookie('uniacid')) {
            $uniacid = cookie('uniacid');
        } else {
            $uniacid = 0;
        }

        cookie('uniacid', $uniacid);

        $url = preg_replace("/\/(\w+)\.php$/i", '', Request::root());


        if(Request::isCli()){
            $path = getcwd() . '/../../data/config.php';
        }else{
            $path = getcwd() . '/../../../data/config.php';
        }
        Config::set([
            'uniacid' => $uniacid, // 应用id
            'is_we7' => is_file($path), // 是否微擎环境
            'cdnurl' => $url,
        ], 'site');

        $database_config = Config::get('database');
        foreach ($database_config['connections'] as &$connection) {
            $connection['query'] = \we\ExtendQuery::class;
        }
        Config::set($database_config, 'database');

        $view_config = Config::get('view');
        $view_config['tpl_replace_string']['__CDN_URL__'] = $url;
        $view_config['tpl_replace_string']['__STATIC__'] = $url.'/resource';
        $view_config['tpl_replace_string']['__ADMIN__'] = $url.'/resource/admin';
        Config::set($view_config, 'view');
    }

    public function fisrtRun()
    {
        $database_config = Config::get('database');

        $database = $database_config['connections'][$database_config['default']]['database'];
        $prefix = $database_config['connections'][$database_config['default']]['prefix'];

        $sql = "SELECT CONCAT('ALTER TABLE `', table_name, '` ADD COLUMN `uniacid` INT(11) NOT NULL DEFAULT 0 COMMENT \"应用id\"') as query FROM information_schema.TABLES WHERE table_schema = '" . $database . "'";
        $list = Db::query($sql);

        foreach ($list as $item) {
            try{
                Db::query($item['query']);
            }catch (\Exception $e){

            }
        }

        // ALTER TABLE ims_xm_mallv3_ad DROP COLUMN weid
        /*$sql = "SELECT CONCAT('ALTER TABLE `', table_name, '` DROP COLUMN `weid`') as query FROM information_schema.TABLES WHERE table_schema = '" . $database . "'";
        $list = Db::query($sql);

        foreach ($list as $item) {
            try{
                Db::query($item['query']);
            }catch (\Exception $e){

            }
        }*/
    }

    // 进行初始数据的填充
    public function initData()
    {
        $database_config = config('database');
        $database_prefix = $database_config['connections']['mysql']['prefix'];


        // 岗位
        $admin_role = Db::name('users_roles')->where('title', '超级管理员')->find();
        if(!$admin_role) {
            $role_id = Db::name('users_roles')->insertGetId([
                'title' => '超级管理员',
                'status' => 1,
                'is_admin' => 0,
                'access' => 'Home',
                'is_allrole' => 1,
            ]);
        }else{
            $role_id = $admin_role['id'];
        }


        // 管理员账号
        $admin_info = Db::name('user')->where('username', 'admin')->find();
        if(!$admin_info) {
            $salt = substr(md5(uniqid()), 8, 8);
            try {
                Db::name('user')->insertGetId([
                    'uuid' => uniqid(rand(1, 10000)),
                    'username' => 'admin',
                    'password' => pass_hash('admin123456', $salt), // admin123456
                    'salt' => $salt,
                    'role_id' => $role_id,
                    'create_time' => time(),
                    'update_time' => time(),
                    'status' => 1,
                    'w7uid' => 0,
                ]);
            }catch (\Exception $exception){
            }
        }

        // 复制基础数据
        $table_list = ['withdraw_mode', 'user_menu', 'bottom_menu', 'diy_page', 'paymethod', 'agreement'];
        foreach ($table_list as $table){
            $data_list = Db::name($table)->where('id', '>', 1)->lock(true)->select();
            if($data_list->isEmpty()) {
                $data_list_base = Db::query('select * from '. $database_prefix . $table. ' where uniacid=0');
                foreach ($data_list_base as $item){
                    unset($item['id']);
                    Db::name($table)->lock(true)->insert($item);
                }
            }
        }

    }

}
